package com.lanzuo.yxd.scanner.scanner.handler;

import com.lanzuo.yxd.scanner.scanner.event.PanelEventPublishUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.nio.charset.StandardCharsets;

/**
 * @author eric
 * 消息处理器
 */
@Slf4j
public class ScannerClientHandler extends IoHandlerAdapter {
    private static final String RECEIVE_END = "\r\n";
    private final Integer lane;
    private final String ip;
    private final String position;
    private final StringBuilder buffer = new StringBuilder();

    public ScannerClientHandler(Integer lane, String ip, String position) {
        this.lane = lane;
        this.ip = ip;
        this.position = position;
    }

    public void onDisconnection() {
        return;
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message instanceof IoBuffer) {
            IoBuffer buf = (IoBuffer) message;
            // 创建字节数组
            byte[] data = new byte[buf.remaining()];
            buf.get(data); // 从 IoBuffer 读取到 byte[]

            String received = new String(data, StandardCharsets.UTF_8);
            buffer.append(received);


            String line = received.replaceAll(RECEIVE_END, "");
            log.info("📩 收到完整消息: {}", line);
            PanelEventPublishUtil.publishPanelMessage(line, lane, ip, position);
        } else {
            log.warn("收到未知类型消息: {}", message.getClass());
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        log.warn("会话已关闭");
        onDisconnection();
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        log.error("MINA_SCANNER 客户端异常", cause);
        onDisconnection();
    }
}